package main

import (
	"fmt"
	"os"
	"time"

	"com.yy.api/my_gateway/internal/cache"
	"com.yy.api/my_gateway/internal/config"
	"com.yy.api/my_gateway/internal/middleware"
	_ "com.yy.api/my_gateway/internal/proxy"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
)

func main() {
	gin.SetMode(gin.ReleaseMode)
	// 初始化配置
	configPath := "config/config.json"
	providersPath := "config/providers.json"
	modelsPath := "config/models.json"
	cfg, err := config.LoadFullConfig(configPath, providersPath, modelsPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Load config failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("Config: %+v\n", cfg)
	// 初始化 Redis 客户端
	redisClient := redis.NewClient(&redis.Options{
		Addr:     cfg.Cache.RateLimit.RedisAddr,
		Password: "",
		DB:       0,
	})

	// 初始化缓存
	chatRateLimitCache := cache.NewRedisCache(redisClient, 5*time.Minute)

	// 初始化反向代理
	// chatProxyFactory := proxy.ChatProxyFactory{}
	// proxies := chatProxyFactory.NewProxies(cfg.Providers)
	// 初始化 Gin 路由
	r := gin.Default()
	// 注册中间件
	r.Use(
		middleware.ReplayableBody(), // 展示请求体
		middleware.Logger(),         // 日志记录
	)

	// 注册路由
	llmChatGroup := r.Group("/chat/completions")
	llmChatGroup.Use(
		middleware.Auth(cfg.Services.LLM.APIKeys),                             // API Key 认证
		middleware.RateLimit(redisClient, cfg.Cache.RateLimit.LimitPerMinute), // 限流
		middleware.Cache(chatRateLimitCache),                                  // 缓存
	)
	// llmChatGroup.POST("", handler.ChatProxyHandler(proxies))

	// 启动服务
	fmt.Printf("Server started at port %d\n", cfg.Port)
	r.Run(fmt.Sprintf("0.0.0.0:%d", cfg.Port))
}
